/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.table;

import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.JEUUID;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.common.MetaBeanService;
import com.je.meta.service.table.MetaTableIndexService;
import com.je.meta.service.table.MetaTableTraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 资源表索引管理
 */
@RestController
@RequestMapping(value = "/je/meta/resourceTable/table/tableIndex")
public class TableIndexController extends AbstractPlatformController {

    @Autowired
    private MetaBeanService metaBeanService;
    @Autowired
    private MetaTableIndexService metaTableIndexService;
    @Autowired
    private MetaTableTraceService metaTableTraceService;

    /**
     * 保存索引
     * @param param
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSave(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String resourceId = getStringParameter(request,"JE_CORE_RESOURCETABLE_ID");
        String orderindex = getStringParameter(request,"SY_ORDERINDEX");
        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", resourceId);
        dynaBean.table("JE_CORE_TABLEINDEX");
        dynaBean.setStr("TABLEINDEX_TYPE","NORMAL");
        dynaBean.set("TABLEINDEX_ISCREATE","0");
        dynaBean.set("TABLEINDEX_UNIQUE","0");
        dynaBean.setStr("TABLEINDEX_CLASSIFY","PRO");
        dynaBean.setStr("TABLEINDEX_TABLECODE",table.getStr("RESOURCETABLE_TABLECODE"));
        dynaBean.setStr("TABLEINDEX_FIELDCODE","");
        dynaBean.setStr("TABLEINDEX_FIELDNAME","");
        dynaBean.set("SY_ORDERINDEX",Integer.valueOf(orderindex));
        dynaBean.set("TABLEINDEX_RESOURCETABLE_ID",resourceId);
        dynaBean.set("TABLEINDEX_NAME", "JE_"+ System.currentTimeMillis());
        commonService.buildModelCreateInfo(dynaBean);
        metaService.insert(dynaBean);
        metaTableTraceService.saveTableTrace("JE_CORE_TABLEINDEX", null, dynaBean, "INSERT", resourceId,"0");
        return BaseRespResult.successResult(dynaBean,MessageUtils.getMessage("common.add.success"));
    }



    /**
     *  移除索引
     * @param param
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doDelete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeIndex(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String ids = getStringParameter(request,"tableIndexIds");
        if(StringUtil.isEmpty(ids)){
            return BaseRespResult.errorResult(MessageUtils.getMessage("index.id.canNotEmpty"));
        }
        Integer count= metaTableIndexService.removeIndex(dynaBean, ids);
        return BaseRespResult.successResult("1000","",MessageUtils.getMessage("common.delete.success"));
    }

    /**
     * 多记录更新
     * @param param
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String strData = param.getStrData();
        if(StringUtil.isEmpty(strData)){
            return BaseRespResult.errorResult(MessageUtils.getMessage("index.canNotEmpty"));
        }
        String result =metaTableIndexService.checkParameter(strData);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        int count = metaTableIndexService.doUpdateList(dynaBean, strData);
        if(count < 0){
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.update.error"));
        }
        return BaseRespResult.successResult("1000","",MessageUtils.getMessage("common.save.success"));
    }

    /**
     * 按照列创建索引
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/createIndexByColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult createIndexByColumn(BaseMethodArgument param,HttpServletRequest request) {
        String funcId = param.getFuncId();
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String columnId = getStringParameter(request,"columnId");
        DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId);
        String tableCode=funcInfo.getStr("FUNCINFO_TABLENAME");
        DynaBean resourceTable = metaBeanService.getResourceTable(tableCode);

        List<DynaBean> tableIndexInfoList = metaService.select(ConditionsWrapper.builder()
                .table("JE_CORE_TABLEINDEX")
                .eq("TABLEINDEX_RESOURCETABLE_ID",resourceTable.getStr("JE_CORE_RESOURCETABLE_ID"))
                .eq("TABLEINDEX_FIELDCODE",dynaBean.getStr("TABLEINDEX_FIELDCODE")));
        if(tableIndexInfoList != null && tableIndexInfoList.size() > 0){
            return BaseRespResult.errorResult(MessageUtils.getMessage("index.exits"));
        }
        DynaBean index = metaTableIndexService.createIndexByColumn(funcInfo,resourceTable, dynaBean.getStr("TABLEINDEX_FIELDCODE"), columnId);
        if(index == null){
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.create.success"));
        }else{
            return BaseRespResult.successResult(index);
        }
    }

    /**
     * 按照列删除索引
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/removeIndexByColumn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeIndexByColumn(BaseMethodArgument param,HttpServletRequest request) {
        String funcId = param.getFuncId();
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String columnId = getStringParameter(request,"columnId");
        String errors = metaTableIndexService.removeIndexByColumn(funcId, dynaBean.getStr("TABLEINDEX_FIELDCODE"), columnId);
        if(StringUtil.isNotEmpty(errors)){
            return BaseRespResult.errorResult(errors);
        }else{
            return BaseRespResult.successResult(MessageUtils.getMessage("common.delete.success"));
        }
    }
}
